package com.yanqu.road.web.controller.usercenter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.impl.admin.AdminCommonDaoImpl;
import com.yanqu.road.dao.impl.servercenter.CrossServerInfoDaoImpl;
import com.yanqu.road.dao.impl.servercenter.CrossUnionServerGroupDaoImpl;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.entity.admin.AdminResult2;
import com.yanqu.road.entity.enums.eChannelType;
import com.yanqu.road.entity.servercenter.CrossServerInfo;
import com.yanqu.road.entity.servercenter.ProcessInfo;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.union.cross.CrossUnionServerGroup;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.CrossServerType;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.controller.usercenter.newadmin.CenterReloadHelper;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/usercenter/admin")
public class CenterCrossGroupAdminController {



    /**
     *  12.2 获取刷新跨服下拉框列表
     */
    @ResponseBody
    @RequestMapping(value = "getCrossServerList", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String getCrossServerList(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");

        List<CrossServerInfo> crossServerInfoList = new CrossServerInfoDaoImpl().getAllChannelCrossServerInfo(channelId);

        AdminResult2 result2 = AdminResult2.defaultInstance();
        for (CrossServerInfo crossServerInfo : crossServerInfoList) {
            if(crossServerInfo.getCrossServerId() == 0){
                continue;
            }
            JSONObject object = new JSONObject();
            object.put("channelId", channelId);
            object.put("crossServerId", crossServerInfo.getCrossServerId());
            object.put("isRankServer", crossServerInfo.getCrossServerType());
            for (ProcessInfo processInfo : crossServerInfo.getProcessInfoList()) {
                if(processInfo.getServerName().equals("web_server")){
                    object.put("address", "http://" + processInfo.getAddress() + ":" + processInfo.getPort() + "/crossws?wsdl");
                }
            }
            result2.getData().add(object);
        }
        return result2.toJsonString();
    }

    /**
     *  12.1 商帮开启时间(固定区服时间+180天，这还要查啥)
     */
    @ResponseBody
    @RequestMapping(value = "unionCampWarOpenTime", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String unionCampWarOpenTime(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");

        JSONArray serverIdArr = jsonObject.getJSONArray("serverIds");

        List<ServerInfo> openServerList = ServerListMgr.getOpenServerList(channelId);

        List<Long> list = new ArrayList<>();
        for (int i = 0; i < serverIdArr.size(); i++) {
            list.add(serverIdArr.getLongValue(i));
        }

        AdminResult2 result2 = AdminResult2.defaultInstance();

        for (ServerInfo serverInfo : openServerList) {
            if(list.size() > 0 && !list.contains(serverInfo.getServerId())){
                continue;
            }
            JSONObject object = new JSONObject();
            object.put("channelId", serverInfo.getChannelId());
            object.put("channelName", eChannelType.forValue(serverInfo.getChannelId()).getName());
            object.put("serverId", serverInfo.getServerId());
            object.put("serverName", serverInfo.getServerName());
            object.put("openTime", DateHelper.getCurrentDateTimeString(serverInfo.getOpenTime() * 1000));
            object.put("openSbTime", DateHelper.getCurrentDateTimeString(serverInfo.getOpenTime() * 1000 + 180 * DateHelper.DAY_MILLIONS));
            result2.getData().add(object);
        }

        return result2.toJsonString();
    }


    /**
     *  12.3 跨服商会系统分组
     */
    @ResponseBody
    @RequestMapping(value = "getCrossUnionServerGroupList", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String getCrossUnionServerGroupList(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");

        Map<Integer, CrossUnionServerGroup> serverGroupMap = new CrossUnionServerGroupDaoImpl().getServerGroupMap(channelId);

        eChannelType channelType = eChannelType.forValue(channelId);
        AdminResult2 result2 = AdminResult2.defaultInstance();
        for (Map.Entry<Integer, CrossUnionServerGroup> groupEntry : serverGroupMap.entrySet()) {
            CrossUnionServerGroup group = groupEntry.getValue();
            JSONObject object = new JSONObject();
            object.put("channelId", group.getChannelId());
            object.put("groupId", group.getGroupId());
            object.put("channelName", channelType.getName());
            object.put("serverIds", StringUtils.listToString(group.getServerList(), ","));
            result2.getData().add(object);
        }
        return result2.toJsonString();
    }

    /**
     *  12.4 新增跨服商会分组
     */
    @ResponseBody
    @RequestMapping(value = "addCrossUnionServerGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String addCrossUnionServerGroup(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        JSONArray list = jsonObject.getJSONArray("list");
        if(list.size() == 0){
            return AdminResult.failMsg("参数有误").toJsonString();
        }

        int maxGroupId = new AdminCommonDaoImpl().getCrossUnionGroupMaxId();

        List<CrossUnionServerGroup> addList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject object = list.getJSONObject(i);
            int channelId = object.getIntValue("channelId");
            String serverIds = object.getString("serverIds");
            CrossUnionServerGroup group = new CrossUnionServerGroup();
            group.setChannelId(channelId);
            group.setGroupId(++maxGroupId);
            group.setState(1);
            group.setServerList(StringUtils.stringToLongList(serverIds, ","));
            addList.add(group);
        }

        boolean result = new AdminCommonDaoImpl().batchInsertCrossUnionServerGroup(addList);
        if(!result){
            return AdminResult.failMsg("更新失败").toJsonString();
        }

        return AdminResult.defaultInstance().toJsonString();

    }

    /**
     *  12.5 修改跨服商会分组
     */
    @ResponseBody
    @RequestMapping(value = "updateCrossUnionServerGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String updateCrossUnionServerGroup(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");
        int groupId = jsonObject.getIntValue("groupId");
        String serverIds = jsonObject.getString("serverIds");
        CrossUnionServerGroup serverGroup = new CrossUnionServerGroup();
        serverGroup.setChannelId(channelId);
        serverGroup.setGroupId(groupId);
        serverGroup.setServerList(StringUtils.stringToLongList(serverIds, ","));
        boolean result = new AdminCommonDaoImpl().updateCrossUnionServerGroup(serverGroup);
        if(!result){
            return AdminResult.failMsg("更新失败").toJsonString();
        }
        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     *  12.6 删除跨服商会分组
     */
    @ResponseBody
    @RequestMapping(value = "delCrossUnionServerGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String delCrossUnionServerGroup(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        int channelId = jsonObject.getIntValue("channelId");
        int groupId = jsonObject.getIntValue("groupId");
        boolean result = new AdminCommonDaoImpl().deleteUnionServerGroup(groupId, channelId);
        if(!result){
            return AdminResult.failMsg("更新失败").toJsonString();
        }
        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     *  12.7 刷新活动跨服
     */
    @ResponseBody
    @RequestMapping(value = "reloadCrossUnionServerGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String reloadCrossUnionServerGroup(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        int channelId = jsonObject.getIntValue("channelId");

        List<ProcessInfo> processInfoList = new ArrayList<>();

        List<CrossServerInfo> serverInfoList = new CrossServerInfoDaoImpl().getAllChannelCrossServerInfo(channelId);
        serverInfoList.removeIf(next -> next.getCrossServerType() != CrossServerType.BANQUET_CROSS);

        for (CrossServerInfo crossServerInfo : serverInfoList) {
            //通知活动跨服刷新活动
            for (ProcessInfo processInfo : crossServerInfo.getProcessInfoList()) {
                if(processInfo.getServerName().equals("cross_server")) {
                    processInfoList.add(processInfo);
                }
            }
        }

        String msg = CenterReloadHelper.crossServerMgrReload(processInfoList, "CrossUnionServerGroupMgr", 20);
        AdminResult result = AdminResult.defaultInstance();
        result.setMsg(msg);
        return result.toJsonString();
    }


    /**
     *  12.8 批量导入(删除所有，再新增)
     */
    @ResponseBody
    @RequestMapping(value = "batchCrossUnionServerGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String batchCrossUnionServerGroup(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        //收集channelId
        JSONArray list = jsonObject.getJSONArray("list");
        if(list.size() == 0){
            return AdminResult.failMsg("参数有误").toJsonString();
        }

        List<Integer> channelIdList = new ArrayList<>();

        List<CrossUnionServerGroup> addList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject object = list.getJSONObject(i);
            int channelId = object.getIntValue("channelId");
            String serverIds = object.getString("serverIds");
            CrossUnionServerGroup group = new CrossUnionServerGroup();
            group.setChannelId(channelId);
            group.setState(1);
            group.setServerList(StringUtils.stringToLongList(serverIds, ","));
            addList.add(group);
            if(!channelIdList.contains(channelId)){
                channelIdList.add(channelId);
            }
        }

        if(channelIdList.size() == 0){
            return AdminResult.failMsg("渠道id缺失").toJsonString();
        }

        boolean del = new AdminCommonDaoImpl().deleteUnionServerGroup(channelIdList);
        if(!del){
            return AdminResult.failMsg("删除渠道下的分组失败").toJsonString();
        }

        int maxGroupId = new AdminCommonDaoImpl().getCrossUnionGroupMaxId();

        for (CrossUnionServerGroup serverGroup : addList) {
            serverGroup.setGroupId(++maxGroupId);
        }

        boolean result = new AdminCommonDaoImpl().batchInsertCrossUnionServerGroup(addList);

        if(!result){
            return AdminResult.failMsg("批量插入失败").toJsonString();
        }

        return AdminResult.defaultInstance().toJsonString();
    }

}
